//
//  ComparisonSelectView.m
//  SecondPage
//
//  Created by winston on 13-5-8.
//  Copyright (c) 2013年 winston. All rights reserved.
//

#import "ComparisonSelectView.h"
#import "../../HondaPro_2/class/AppDelegate.h"
#import "ComparisonSelectCell.h"
#import "../../ResourceLoader/ResourceLoader/ResourceLoader.h"

@implementation ComparisonSelectView

@synthesize selectBrandId;
@synthesize selectSeriesId;
@synthesize selectAutoId;
@synthesize blockCancle;
@synthesize blockSelected;

static ComparisonSelectView * _instance = nil;

+(ComparisonSelectView *)instance
{
    @synchronized(_instance)
    {
        if(_instance==nil)
        {
            _instance = [[self alloc]init];
        }
        return _instance;
    }
}

- (id)init
{
    self = [super init];
    if (self)
    {
        CGRect frame = CGRectMake(0, 0, 1024, 768);
        self.frame = frame;
        
        bgControl = [[UIControl alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        [self addSubview:bgControl];
        [bgControl release];
        [bgControl setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.4]];
        [bgControl addTarget:self action:@selector(onCancelSelectTap:) forControlEvents:UIControlEventTouchUpInside];
        
        
        contentView = [[UIImageView alloc]initWithFrame:CGRectMake((frame.size.width-615)/2, (frame.size.height-676)/2+768, 615, 676)];
        [contentView setUserInteractionEnabled:TRUE];
        [contentView setImage:[UIImage imageNamed:@"presentView@2x~ipad.png"]];
        [self addSubview:contentView];
        [contentView release];
        
        
        titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, 50, contentView.frame.size.width-100, 50)];
        [titleLabel setBackgroundColor:[UIColor clearColor]];
        [titleLabel setTextColor:[UIColor blackColor]];
        [titleLabel setFont:[UIFont fontWithName:@"Arial" size:20]];
        [titleLabel setText:@"添加竞品"];
        [contentView addSubview:titleLabel];
        [titleLabel release];
        
        finishBtn = [[UIButton alloc]initWithFrame:CGRectMake(466, 50, 80, 40)];
        [finishBtn setImage:[UIImage imageNamed:@"button.png"] forState:UIControlStateNormal];
        [finishBtn addTarget:self action:@selector(onDidSelectedTap:) forControlEvents:UIControlEventTouchUpInside];
        [contentView addSubview:finishBtn];
        [finishBtn release];
        
        UILabel* nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, finishBtn.frame.size.width, finishBtn.frame.size.height)];
        nameLabel.backgroundColor = [UIColor clearColor];
        nameLabel.textAlignment = NSTextAlignmentCenter;
        nameLabel.font = [UIFont fontWithName:@"Arial" size:15];
        [finishBtn addSubview:nameLabel];
        [nameLabel release];
        [nameLabel setTextColor:[UIColor whiteColor]];
        [nameLabel setText:@"完成"];
        
        
        lineView = [[UIImageView alloc]initWithFrame:CGRectMake(60, 100, contentView.frame.size.width-120, 2.5)];
        [lineView setImage:[UIImage imageNamed:@"redline@2x~ipad.png"]];
        [contentView addSubview:lineView];
        [lineView release];
    

        UIView * tableContentView = [[UIView alloc]initWithFrame:CGRectMake(60, 110, contentView.frame.size.width-120, contentView.frame.size.height-160)];
        [tableContentView setBackgroundColor:[UIColor clearColor]];
        [tableContentView setClipsToBounds:TRUE];
        [contentView addSubview:tableContentView];
        [tableContentView release];
        
        mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, tableContentView.frame.size.width, tableContentView.frame.size.height)];
        mainTable.delegate = self;
        mainTable.dataSource = self;
        [mainTable setBackgroundColor:[UIColor clearColor]];
        mainTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        [tableContentView addSubview:mainTable];
        [mainTable release];
        
        
        subTable = [[UITableView alloc] initWithFrame:CGRectMake(tableContentView.frame.size.width, 0, tableContentView.frame.size.width, tableContentView.frame.size.height)];
        subTable.delegate = self;
        subTable.dataSource = self;
        [subTable setBackgroundColor:[UIColor clearColor]];
        subTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        [tableContentView addSubview:subTable];
        [subTable release];
    
        [self InitData];
    }
    return self;
}

-(void)InitData
{
    mainTableArray = [NSMutableArray new];
    
    [mainTableArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"品牌",@"key",@"未选择",@"value",nil]];
    
    [mainTableArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"车系",@"key",@"未选择",@"value",nil]];
    
    [mainTableArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"车型",@"key",@"未选择",@"value",nil]];

    isMainTableShowed = TRUE;
    
    [mainTable reloadData];
    
    currentSubIndex = -1;
}

-(void)showWithDidSelectBlock:(DidSelectedBlcok)block1 cancelSelectBlock:(CancelSelectedBlock)block2
{
    self.blockSelected = block1;
    self.blockCancle = block2;
    
    if(self.superview!=nil)
    {
        [self removeFromSuperview];
    }

    [((AppDelegate*)([UIApplication sharedApplication].delegate)).window.rootViewController.view addSubview:self];
    
    [bgControl setAlpha:0];
    
    [[UIApplication sharedApplication]beginIgnoringInteractionEvents];
    
    [UIView beginAnimations:@"showView" context:nil];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
    
    [bgControl setAlpha:1];
    [contentView setFrame:CGRectMake(contentView.frame.origin.x,
                                     (self.frame.size.height-contentView.frame.size.height)/2,
                                     contentView.frame.size.width,
                                     contentView.frame.size.height)];
    
    
    [UIView commitAnimations];
}

-(void)onCancelSelectTap:(id)sender
{
    [self closeSelf:@"closeView"];
}

-(void)onDidSelectedTap:(id)sender
{
    if(self.selectAutoId<=0) return;
    
    [self closeSelf:@"finishSelect"];
}

-(void)closeSelf:(NSString*)type
{
    [[UIApplication sharedApplication]beginIgnoringInteractionEvents];
    
    [UIView beginAnimations:type context:nil];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
    
    [bgControl setAlpha:0];
    [contentView setFrame:CGRectMake(contentView.frame.origin.x,
                                     self.frame.size.height,
                                     contentView.frame.size.width,
                                     contentView.frame.size.height)];
    
    
    [UIView commitAnimations];
}

//转到首页
-(void)gotoMainTable:(NSDictionary*)data withIndex:(NSInteger)index
{
    isMainTableShowed = TRUE;
    currentSubIndex = -1;
    
    if([data objectForKey:@"specid"]!=nil)
    {
        //@hanhaidi@0816@显示指导价
        //[[mainTableArray objectAtIndex:2]setObject:[data objectForKey:@"name"] forKey:@"value"];
        NSString *nameAndPrice = [NSString stringWithFormat:@"%@（%@）",[data objectForKey:@"name"],[data objectForKey:@"paravalue"]];
        [[mainTableArray objectAtIndex:2]setObject:nameAndPrice forKey:@"value"];
         selectAutoId = [[data objectForKey:@"specid"]intValue];
    }
    else if([data objectForKey:@"seriesid"]!=nil)
    {
        [[mainTableArray objectAtIndex:1]setObject:[data objectForKey:@"name"] forKey:@"value"];
        NSInteger newSeriesId = [[data objectForKey:@"seriesid"]intValue];
        if(selectSeriesId!=newSeriesId)
        {
            selectSeriesId = newSeriesId;
            selectAutoId = 0;
            [[mainTableArray objectAtIndex:2]setObject:@"未选择" forKey:@"value"];
        }
    }
    else if([data objectForKey:@"brandid"]!=nil)
    {
        [[mainTableArray objectAtIndex:0]setObject:[data objectForKey:@"name"] forKey:@"value"];
        NSInteger newBrandId  = [[data objectForKey:@"brandid"]intValue];
        if(selectBrandId!=newBrandId)
        {
            selectBrandId = newBrandId;
            selectSeriesId = 0;
            selectAutoId = 0;
            [[mainTableArray objectAtIndex:1]setObject:@"未选择" forKey:@"value"];
            [[mainTableArray objectAtIndex:2]setObject:@"未选择" forKey:@"value"];
        }
    }
    
    [mainTable reloadData];
    
    
    [[UIApplication sharedApplication]beginIgnoringInteractionEvents];
    
    [UIView beginAnimations:@"gotoMainTable" context:nil];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
    
    [mainTable setFrame:CGRectMake(0,
                                   0,
                                   mainTable.frame.size.width,
                                   mainTable.frame.size.height)];
    
    [subTable setFrame:CGRectMake(subTable.frame.size.width,
                                  0,
                                  subTable.frame.size.width,
                                  subTable.frame.size.height)];
    
    
    [UIView commitAnimations];
}

//转到第二页
-(void)gotoSubTable:(NSDictionary*)data withIndex:(NSInteger)index
{
    currentSubIndex = index;
    SafeRelease(subTableArray);
    
    subTableArray = [NSMutableArray new];

    if(index==0)
    {
        NSArray * branArray = [[ResourceLoader getInstance]getAllBrands];
    
        NSMutableDictionary * currentDic = nil;
        
        for(NSDictionary * dic in branArray)
        {
            NSString * sectionTitle = [[dic objectForKey:@"name"]substringWithRange:NSMakeRange(0, 1)];
            if(currentDic==nil||![[currentDic objectForKey:@"sectiontitle"]isEqualToString:sectionTitle])
            {
                currentDic = [NSMutableDictionary dictionaryWithCapacity:2];
                [currentDic setObject:sectionTitle forKey:@"sectiontitle"];
                [currentDic setObject:[NSMutableArray array] forKey:@"datas"];
                [subTableArray addObject:currentDic];
            }
        
            NSMutableDictionary * brandDic = [NSMutableDictionary dictionaryWithDictionary:dic];
            [brandDic setObject:[dic objectForKey:@"name"] forKey:@"key"];
            [brandDic setObject:@"" forKey:@"value"];
            [[currentDic objectForKey:@"datas"]addObject:brandDic];
        }
    }
    else if(index==1)
    {
        NSArray * seriesArray = [[ResourceLoader getInstance]getSeriesByBrand:selectBrandId];
        
        for(NSDictionary * dic in seriesArray)
        {
            NSMutableDictionary * brandDic = [NSMutableDictionary dictionaryWithDictionary:dic];
            [brandDic setObject:[dic objectForKey:@"name"] forKey:@"key"];
            [brandDic setObject:@"" forKey:@"value"];
            [subTableArray addObject:brandDic];
        }
    }
    else if(index==2)
    {
        NSArray * specArray = [[ResourceLoader getInstance]getSpecBySeriesId:selectSeriesId brand:selectBrandId];
        
        for(NSDictionary * dic in specArray)
        {
            NSMutableDictionary * brandDic = [NSMutableDictionary dictionaryWithDictionary:dic];
            //@hanhaidi@0816@显示指导价
            //[brandDic setObject:[dic objectForKey:@"name"] forKey:@"key"];
            NSString *nameAndPrice = [NSString stringWithFormat:@"%@（%@）",[dic objectForKey:@"name"],[dic objectForKey:@"paravalue"]];
            [brandDic setObject:nameAndPrice forKey:@"key"];
            [brandDic setObject:@"" forKey:@"value"];
            [subTableArray addObject:brandDic];
        }
    }
    if([subTableArray count]==0)
    {
        [subTableArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"没有匹配结果", @"key",@"没有匹配结果",@"value",nil]];
    }

    isMainTableShowed = FALSE;
  
    [subTable reloadData];
    
    [[UIApplication sharedApplication]beginIgnoringInteractionEvents];
    
    [UIView beginAnimations:@"gotoSubTable" context:nil];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
    
    [mainTable setFrame:CGRectMake(-mainTable.frame.size.width,
                                     0,
                                     mainTable.frame.size.width,
                                     mainTable.frame.size.height)];
    
    [subTable setFrame:CGRectMake(0,
                                   0,
                                   subTable.frame.size.width,
                                   subTable.frame.size.height)];
    
    
    [UIView commitAnimations];
}

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
  
    [[UIApplication sharedApplication] endIgnoringInteractionEvents];

    if([animationID isEqualToString:@"closeView"])
    {
        if(blockCancle)
            blockCancle();
        [self removeFromSuperview];

    }
    else if([animationID isEqualToString:@"finishSelect"])
    {
        if(blockSelected)
            blockSelected();
        [self removeFromSuperview];
    }
}

#pragma mark - TableView Delegate & DataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(isMainTableShowed)
    {
        return [mainTableArray count];
    }
    else
    {
        if(currentSubIndex==0)
        {
            return [[[subTableArray objectAtIndex:section]objectForKey:@"datas"]count];
        }
        return [subTableArray count];
    }
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    if(!isMainTableShowed&&currentSubIndex==0)
    {
        return  [subTableArray count];
    }
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = isMainTableShowed?@"MainTableCell":@"SubTableCell";
    
    ComparisonSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[ComparisonSelectCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSArray * array = isMainTableShowed?mainTableArray:subTableArray;
    NSDictionary * data =nil;
    if(currentSubIndex==0)
    {
        NSArray * sectionArray = [[array objectAtIndex:indexPath.section]objectForKey:@"datas"];
        data = [sectionArray objectAtIndex:indexPath.row];
    }
    else
    {
        data = [array objectAtIndex:indexPath.row];
    }
    [cell loadData:data withStyle:isMainTableShowed];

    
    if(!isMainTableShowed)
    {
        BOOL isSelect = FALSE;
        if([data objectForKey:@"specid"]!=nil)
        {
          if([[data objectForKey:@"specid"]intValue]==selectAutoId)
          {
              isSelect = TRUE;
          }
        }
        else if([data objectForKey:@"seriesid"]!=nil)
        {
            if([[data objectForKey:@"seriesid"]intValue]==selectSeriesId)
            {
                isSelect = TRUE;
            }
        }
        else
        {
            if([[data objectForKey:@"brandid"]intValue]==selectBrandId)
            {
                isSelect = TRUE;
            }
        }
        cell.accessoryType = isSelect? UITableViewCellAccessoryCheckmark:UITableViewCellAccessoryNone;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray * array = isMainTableShowed?mainTableArray:subTableArray;
    
   if(isMainTableShowed)
   {
       NSDictionary * data = [array objectAtIndex:indexPath.row];
       [self gotoSubTable:data withIndex:indexPath.row];
   }
   else
   {
       NSDictionary  * data = nil;
       
       if(currentSubIndex==0)
       {
           NSDictionary * brandData = [array objectAtIndex:indexPath.section];
           data = [[brandData objectForKey:@"datas"]objectAtIndex:indexPath.row];
           [self gotoMainTable:data withIndex:indexPath.row];
       }
       else
       {
            NSDictionary * data = [array objectAtIndex:indexPath.row];
           [self gotoMainTable:data withIndex:indexPath.row];
       }
   }
}


-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if(!isMainTableShowed&&currentSubIndex==0)
    {
        UIView * sectionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, subTable.frame.size.width, 0)];
        return [sectionView autorelease];
    }
    return nil;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if(!isMainTableShowed&&currentSubIndex==0)
    {
        NSMutableArray *toBeReturned = [[NSMutableArray alloc]init];
        
        for(NSDictionary * dic in subTableArray)
        {
            [toBeReturned addObject:[dic objectForKey:@"sectiontitle"]];
        }
        
        return [toBeReturned autorelease];
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSInteger count = 0;

    if(!isMainTableShowed&&currentSubIndex==0)
    {
        for(NSDictionary * dic in subTableArray)
        {
            if([[dic objectForKey:@"sectiontitle"]isEqualToString:title])
                return count;
            count++;
        }
    }
    
    return 0;
}

-(void)dealloc
{
    [super dealloc];
}
@end
